package com.lfs.dingtalk.robot.web;

import com.alibaba.fastjson.JSON;
import com.aliyun.dingtalkcontact_1_0.models.GetUserHeaders;
import com.aliyun.dingtalkcontact_1_0.models.GetUserResponse;
import com.aliyun.dingtalkcontact_1_0.models.GetUserResponseBody;
import com.aliyun.dingtalkoauth2_1_0.models.GetUserTokenRequest;
import com.aliyun.dingtalkoauth2_1_0.models.GetUserTokenResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

import static com.lfs.dingtalk.robot.constants.CommonConstant.APP_KEY;
import static com.lfs.dingtalk.robot.constants.CommonConstant.APP_SECRET;

@RequestMapping("/login")
@RestController
@Slf4j
public class LoginController {


    static com.aliyun.dingtalkoauth2_1_0.Client authClient() throws Exception {
        return new com.aliyun.dingtalkoauth2_1_0.Client(new Config() {{
            protocol = "https";
            regionId = "central";
        }});
    }

    static com.aliyun.dingtalkcontact_1_0.Client contactClient() throws Exception {
        return new com.aliyun.dingtalkcontact_1_0.Client(new Config() {{
            protocol = "https";
            regionId = "central";
        }});
    }


    @GetMapping("/dingtalk/callback/**")
    public String userInfo(@RequestParam(value = "authCode") String authCode) {
        try {
            log.info("回调开始，授权码authCode={}", authCode);
            com.aliyun.dingtalkoauth2_1_0.Client client  = authClient();
            GetUserTokenRequest getUserTokenRequest = new GetUserTokenRequest()
                    .setClientId(APP_KEY)            //AppKey
                    .setClientSecret(APP_SECRET) //AppSecret
                    .setCode(authCode)
                    .setGrantType("authorization_code");
            GetUserTokenResponse getUserTokenResponse = client.getUserToken(getUserTokenRequest);  //SDK的http请求
            //这里是用户个人token，只有用户信息，无关组织
            String userToken = getUserTokenResponse.getBody().getAccessToken();
            GetUserResponseBody userinfo = getUserinfo(userToken);
//            String accessToken = this.getAccessToken();
            return userinfo.getUnionId();
        }catch (Exception e){
            log.error("回调失败", e);
            throw new RuntimeException("回调失败");
        }
    }

//
//    /**
//     * 获取企业的accessToken
//     *
//     * @return 企业tokne
//     * @throws IOException
//     */
//    public String getAccessToken() throws IOException {
//        try (Response response = new OkHttpClient().newCall(new Request.Builder()
//                .url(URI + "?appkey=" + APP_ID + "&appsecret=" + APP_SECRET)
//                .build()).execute()) {
//            if (!response.isSuccessful()) {
//                throw new IOException("错误信息：" + response);
//            }
//            return response.body() != null ? JSON.parseObject(response.body().string(), TokenBody.class).getAccess_token() : null;
//        }
//    }


    /**
     * 获取用户个人信息
     *
     * @param accessToken 钉钉的token
     * @return 用户钉钉基础信息
     * @throws Exception
     */
    public GetUserResponseBody getUserinfo(String accessToken) throws Exception {
        com.aliyun.dingtalkcontact_1_0.Client client = contactClient();
        GetUserHeaders getUserHeaders = new GetUserHeaders();
        getUserHeaders.xAcsDingtalkAccessToken = accessToken;
        //获取用户个人信息，如需获取当前授权人的信息，unionId参数必须传me
        GetUserResponse user = client.getUserWithOptions("me", getUserHeaders, new RuntimeOptions());
        log.info("来自钉钉的用户信息：{}", JSON.toJSONString(user));
        return user.getBody();
    }


    /**
     * 钉钉access_token响应体
     */
    @AllArgsConstructor
    @NoArgsConstructor
    @Data
    private static class TokenBody {
        public Integer errcode;
        public String access_token;
        public String errmsg;
        public Integer expires_in;
    }
}
